package com.idlecode.util;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.vfs.VirtualFile;

import java.io.IOException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @program: IdleCode
 * @description
 * @author: rongjuwei
 * @create: 2025-04-03 09:49
 **/
public class ProjectUtil {

    /**
     * 获取项目中jdk版本号
     */
    public static String getProjectJdkVersion(Project project) {
        // 通过 ProjectRootManager 获取项目的 JDK（SDK）
        Sdk projectSdk = ProjectRootManager.getInstance(project).getProjectSdk();

        if (projectSdk == null) {
            return null;
        }

        // 获取完整的 JDK 版本字符串
        String versionString = projectSdk.getVersionString();
        if (versionString == null) {
            return null;
        }

        // 使用正则提取 JDK 主要版本号
        Pattern pattern = Pattern.compile("(\\d+)(\\.\\d+)?");
        Matcher matcher = pattern.matcher(versionString);

        if (matcher.find()) {
            return matcher.group(1).equals("1") ? matcher.group(2).substring(1) : matcher.group(1);
        }

        return null;
    }

    /**
     * 获取项目中jdk基础包名
     */
    public static String getJdkBasePackage(Project project) {
        String projectJdkVersion = getProjectJdkVersion(project);
        if (projectJdkVersion == null && "".equals(projectJdkVersion.trim())) {
            return "javax";
        }
        if (Integer.parseInt(projectJdkVersion) >= 9) {
            return "jakarta";
        } else {
            return "javax";
        }
    }

    /**
     * 获取项目中tomcat版本号
     */
    public static String getTomcatBasePackage(Project project) {
        for (Module module : ModuleManager.getInstance(project).getModules()) {
            for (OrderEntry entry : ModuleRootManager.getInstance(module).getOrderEntries()) {
                if (entry == null) {
                    continue;
                }
                if (!(entry instanceof LibraryOrderEntry)) {
                    continue;
                }

                LibraryOrderEntry libraryEntry = (LibraryOrderEntry) entry;

                if (!libraryEntry.getLibraryName().contains("org.apache.tomcat.embed")) {
                    continue;
                }
                VirtualFile[] rootFiles = libraryEntry.getRootFiles(OrderRootType.CLASSES);
                for (VirtualFile rootFile : rootFiles) {
                    //判断该tomcat包里的根目录是jakarta还是javax
                    if (rootFile.getPresentableUrl().endsWith(".jar")) { // 只处理 JAR 文件
                        String packageType = checkJarForPackageType(rootFile.getPresentableUrl());
                        if (packageType != null) {
                            return packageType;
                        }
                    }
                }
            }
        }
        return "javax"; // 默认值
    }

    private static String checkJarForPackageType(String jarPath) {
        try (ZipFile zipFile = new ZipFile(jarPath)) {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String entryName = entry.getName();
                System.out.println("entryName = " + entryName);
                if (entryName.startsWith("jakarta/")) {
                    return "jakarta";
                }
                if (entryName.startsWith("javax/")) {
                    return "javax";
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
